package com.sun.springbootfiledownload.controller;

import com.sun.springbootfiledownload.dto.UploadTask;
import com.sun.springbootfiledownload.enums.UploadTaskStatus;
import com.sun.springbootfiledownload.service.OssUploadQueueService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.coyote.BadRequestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/api/oss/queue")
public class OssQueueUploadController {

    @Autowired
    private OssUploadQueueService uploadQueueService;

    // 文件大小限制（可在application.yml配置）
    @Value("${spring.servlet.multipart.max-file-size:100MB}")
    private String maxFileSize;

    @PostMapping(value="/submitUpload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<UploadResponse> submitUpload(
            @RequestPart("files") MultipartFile[] files,
            @RequestParam(required = false) String folder) throws IOException {
        // 1. 参数校验
        if (files == null || files.length == 0) {
            throw new BadRequestException("至少上传一个文件");
        }

        // 2. 批量提交任务
        List<UploadTask> tasks = new ArrayList<>();
        for (MultipartFile file : files) {
            try {
                UploadTask task = uploadQueueService.submitUploadTask(file, folder);
                tasks.add(task);
            } catch (IOException e) {
                log.error("文件处理失败: {}", file.getOriginalFilename(), e);
                tasks.add(new UploadTask(
                        "FAILED-" + UUID.randomUUID(),
                        file.getOriginalFilename(),
                        file.getSize(),
                        folder,
                        UploadTaskStatus.FAILED,
                        0,
                        null,
                        "文件读取失败: " + e.getMessage(),
                        Instant.now(),
                        file.getBytes()
                ));
            }
        }

        // 3. 构建响应
        return ResponseEntity.accepted().body(
                new UploadResponse(
                        "任务已接收",
                        tasks.stream().map(this::toTaskDto).toList()
                )
        );
    }

    // 任务对象转换
    private UploadTaskDTO toTaskDto(UploadTask task) {
        return new UploadTaskDTO(
                task.getTaskId(),
                task.getFileName(),
                task.getStatus().name(),
                task.getProgress()
        );
    }

    // 响应DTO
    @Data
    @AllArgsConstructor
    static class UploadResponse {
        private String message;
        private List<UploadTaskDTO> tasks;
    }

    // 简化的任务DTO
    @Data
    @AllArgsConstructor
    static class UploadTaskDTO {
        private String taskId;
        private String fileName;
        private String status;
        private int progress;
    }
}
